package com.dabai.magiskmodulerepair;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.dabai.magiskmodulerepair.adapter.FileAdapter;
import com.dabai.magiskmodulerepair.bean.FileInfo;
import com.dabai.magiskmodulerepair.utils.AssetsUtils;
import com.dabai.magiskmodulerepair.utils.DabaiUtils;
import com.dabai.magiskmodulerepair.utils.QMUIUtils;
import com.dabai.magiskmodulerepair.utils.ZipUtil2;
import com.dabai.magiskmodulerepair.utils.ZipUtils;
import com.permissionx.guolindev.PermissionX;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.tencent.bugly.Bugly;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import me.rosuh.filepicker.bean.FileItemBeanImpl;
import me.rosuh.filepicker.config.AbstractFileFilter;
import me.rosuh.filepicker.config.FilePickerManager;
import me.rosuh.filepicker.filetype.RasterImageFileType;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "DBLog";

    RecyclerView recyclerView;
    private List<String> fileList;
    QMUIEmptyView tip;
    private FileAdapter fileAdapter;
    private QMUIPopup qmuiPopup;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);



        PermissionX.init(this).permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request((allGranted, grantedList, deniedList) -> {
                            if (!allGranted) {
                                new QMUIDialog.MessageDialogBuilder(MainActivity.this)
                                        .setTitle("警告")
                                        .setCancelable(false)
                                        .setMessage("缺少必须的储存权限,程序不能运行!")
                                        .addAction("退出", (dialog, index) -> {
                                            dialog.dismiss();
                                            finish();
                                        })
                                        .show();
                            }else {
                                if (DabaiUtils.isActivityFirstOpen(this)){
                                    QMUIUtils.showDialogText(this,getString(R.string.tip));
                                }
                            }
                        });


        tip = findViewById(R.id.tip);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, 1));

        QMUITopBarLayout topbar = findViewById(R.id.topbar);

        topbar.setTitle("Magisk模块修复").setTextColor(ContextCompat.getColor(this, R.color.qmui_config_color_black));
        topbar.setBackgroundColor(ContextCompat.getColor(this, R.color.qmui_config_color_white));
        // topbar.setSubTitle("低版本的模块不显示在高版本的管理器");



        topbar.addLeftImageButton(R.drawable.ic_add1, R.id.topbar).setOnClickListener(v -> FilePickerManager.INSTANCE
                .from(MainActivity.this)
                .filter(new AbstractFileFilter() {
                    @Override
                    public @NotNull ArrayList<FileItemBeanImpl> doFilter(@NotNull ArrayList<FileItemBeanImpl> arrayList) {


                        Iterator iterator = arrayList.iterator();
                        while (iterator.hasNext()) {
                            FileItemBeanImpl item = (FileItemBeanImpl) iterator.next();
                            // 如果是文件夹则略过
                            if (item.isDir()) continue;
                            // 判断文件类型是否是图片
                            if (!item.getFilePath().endsWith(".zip")) {
                                iterator.remove();
                            }
                        }

                        return arrayList;
                    }
                })
                .forResult(FilePickerManager.REQUEST_CODE));

        topbar.addRightImageButton(R.drawable.ic_build2, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (fileAdapter != null) {
                    if (fileAdapter.getData().size() <= 0) {
                        QMUIUtils.showDialogText(MainActivity.this, "无文件!");
                        return;
                    }
                    new QMUIDialog.MessageDialogBuilder(MainActivity.this)
                            .setTitle("提示")
                            .setMessage("确定修复这" + fileAdapter.getData().size() + "个文件嘛?")
                            .addAction("取消", (dialog, index) -> dialog.dismiss())
                            .addAction("确认", (dialog, index) -> {
                                dialog.dismiss();
                                try {
                                    work();
                                } catch (Exception e) {
                                    Toast.makeText(MainActivity.this, "修复失败!", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .show();
                } else {
                    QMUIUtils.showDialogText(MainActivity.this, "无文件!");
                }
            }
        });

    }


    int j,current;

    private void work() throws Exception {

        ArrayList<FileInfo> oldFileInfo = (ArrayList<FileInfo>) fileAdapter.getData();
        ArrayList<String> errFiles = new ArrayList<>();
        current = 0;

        new Thread(new Runnable() {
            @Override
            public void run() {


                for (int i = 0; i < oldFileInfo.size(); i++) {
                    j = i;
                    runOnUiThread(() -> qmuiPopup = QMUIUtils.showPopupText(MainActivity.this, fileAdapter.getViewByPosition(j, R.id.textView1), "正在修复第" + (j + 1) + "个"));

                    String name = oldFileInfo.get(i).getName();
                    String path = oldFileInfo.get(i).getPath();
                    String unZipDir = getExternalCacheDir().getPath() + "/" + name;
                    try {

                        //解压这玩意 start
                        ZipUtils.UnZipFolder(path, unZipDir);

                        //复制文件替换到 模块内
                        AssetsUtils.copyFile(
                                getApplicationContext()
                                , "update-binary"
                                , getExternalCacheDir().getPath() + "/" + name + "/META-INF/com/google/android/update-binary");

                        String soc = getExternalCacheDir().getPath() + "/" + name;
                        String tag = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/MMR_" + name;

                        //再把这玩意压缩回去 end
                        File[] arrayList = new File(soc).listFiles();
                        ZipUtil2.zipFiles(Arrays.asList(arrayList), new File(tag));

                        current++;

                        runOnUiThread(() -> qmuiPopup.dismiss());

                    } catch (Exception e) {
                        runOnUiThread(() -> {
                            qmuiPopup.dismiss();
                            errFiles.add(name);
                        });
                    }
                }
                runOnUiThread(() -> QMUIUtils.showDialogText(MainActivity.this,
                        (errFiles.size()>0 ? errFiles+"修复失败,另外":"") +current+"个文件已修复完成"+",至 " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/MMR_*.zip"));
            }
        }).start();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == FilePickerManager.REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                fileList = FilePickerManager.INSTANCE.obtainData();
                ArrayList<FileInfo> fileInfos = new ArrayList<>();

                for (String path : fileList) {

                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(new File(path).getName());
                    fileInfo.setPath(path);
                    fileInfos.add(fileInfo);

                }


                fileAdapter = new FileAdapter(fileInfos);
                recyclerView.setAdapter(fileAdapter);


                if (fileAdapter.getData().size() > 0) {
                    tip.setVisibility(View.GONE);
                }

                fileAdapter.setAnimationEnable(true);
                fileAdapter.setAnimationFirstOnly(false);
                fileAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInRight);
                // 设置点击事件
                fileAdapter.setOnItemClickListener((adapter, view, position) -> {
                    String path = fileInfos.get(position).getPath();
                    QMUIUtils.showPopupText(this, view, path);
                });

                fileAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                        String name = fileInfos.get(position).getName();
                        String path = fileInfos.get(position).getPath();
                        fileAdapter.removeAt(position);
                        if (fileAdapter.getData().size() <= 0) {
                            tip.setVisibility(View.VISIBLE);
                        }
                        return false;
                    }
                });


            } else {
                //DabaiUtils.showToast(MainActivity.this, "你没有选择任何文件!");
            }
        }

    }
}